package com.lagou.rocket.service;

import com.lagou.rocket.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private OrderService orderService;

    @Resource
    private WarehouseService warehouseService;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expireKey = message.toString();

        if (expireKey.startsWith("order:")) {
            String id = expireKey.split(":")[1];

            Order order = orderService.getOrder(id);

            orderService.invalidOrder(id);

            log.info("订单失效，库存还原");
            warehouseService.stock(order.getName(), order.getNum());
            warehouseService.realstock(order.getName(), order.getNum());
        }

    }

}

